package clang.ir;

import clang.Datatype;
import fixedpoint.DataflowException;

/**
 * Bitwise shift
 */
public class Shift extends Operator {

    private int distance;

    public Shift(int distance) {
        child = new Node[1];
        this.distance = distance;
    }

    public int getDistance() {
        return distance;
    }

    // TODO Review C-lang cast
    @Override
    public String getRuntimeExpression() throws DataflowException {
        String childRuntimeValue = child[0].getRuntimeValueWithWrap();

        String result;
        if (distance < 0) {
            // Shift to left
            result = childRuntimeValue + " << " + (-distance);
        } else {
            if (distance > 0) {
                // Shift to right
                String cast = "";
                Datatype childDatatype = child[0].datatype;
                if (childDatatype != null) {
                    cast = wrap(childDatatype.toString());
                }
                result = cast + childRuntimeValue + " >> " + distance;
            } else {
                throw new DataflowException("Shift without distance");
            }
        }
        return result;
    }
}
